package com.abc.scholarship.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.abc.scholarship.common.enums.StatusEnum;
import com.abc.scholarship.domain.dto.ScholarshipDTO;
import com.abc.scholarship.domain.entity.Scholarship;
import com.abc.scholarship.domain.vo.resp.ApiResult;
import com.abc.scholarship.exception.BusinessException;
import com.abc.scholarship.mapper.ScholarshipMapper;
import com.abc.scholarship.service.ScholarshipService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 奖学金表 服务实现类
 * </p>
 *
 * @author jzw
 * @since 2024-07-02
 */
@Service
@RequiredArgsConstructor
public class ScholarshipServiceImpl extends ServiceImpl<ScholarshipMapper, Scholarship> implements ScholarshipService {
    private final ScholarshipMapper scholarshipMapper;
    @Override
    public void setStatusByIds(List<Long> idList, Integer status) {
        scholarshipMapper.setStatusByIds(idList,status);
    }

    @Override
    public void MUpdateById(Scholarship scholarship) {
        if (scholarship.getStatus() == null) {
            if(scholarship.getRatio() < 1 || getSumRatio() + scholarship.getRatio() > 100){
                throw new BusinessException("比例错误");
            }
            scholarshipMapper.updateById(scholarship);
            return;
        }

        if (scholarship.getStatus().equals(StatusEnum.FROZEN.getValue())) {
            scholarship.setStatus(StatusEnum.NORMAL.getValue());
        } else if (scholarship.getStatus().equals(StatusEnum.NORMAL.getValue())) {
            scholarship.setStatus(StatusEnum.FROZEN.getValue());
        } else throw new BusinessException("状态异常，请联系管理员");
        scholarshipMapper.updateById(scholarship);
    }

    @Override
    public String insert(ScholarshipDTO scholarshipDTO) {
        if (scholarshipDTO.getScholarshipName() == null || scholarshipDTO.getScholarshipName().isEmpty()) {
            return "奖学金名字不能为空";
        }
        if(scholarshipDTO.getRatio() < 1 || getSumRatio() + scholarshipDTO.getRatio() > 100){
            return "比例错误";
        }
        scholarshipMapper.insert(BeanUtil.copyProperties(scholarshipDTO, Scholarship.class));
        return null;
    }

    //查询数据库的人数比例和
    private Integer getSumRatio(){
        Integer sumRatio = scholarshipMapper.getSumRatio();
        return sumRatio == null ? 0 : sumRatio;
    }
}
